// pages/index-inside-page/hideenDanger/hideenDanger.js
import {
  reqhiddenDangerAdd
} from "../../../../request/api"
import {
  showMsg
} from '../../../../utils/config.js'
import {
  validateEmoji
} from '../../../../utils/validate.js'

var app = getApp()

//引入插件：微信同声传译
const plugin = requirePlugin('WechatSI');
//获取全局唯一的语音识别管理器recordRecoManager
const manager = plugin.getRecordRecognitionManager();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    navHeight: app.globalData.navHeight + 'px', //头部距离

    rolename: '',

    showUnitSelection: false, //是否展示单位选择弹窗
    orgId: '',
    orgName: '',

    option: [{
        text: '低电量',
        value: 2
      },
      {
        text: '故障',
        value: 98
      },
      {
        text: '其他',
        value: 99
      },
    ],
    handleWay: 2,
    handleWayValue: '',
    handleOptionValue: '',
    fileImageList: [],
    fileVideoList: [],
    recordState: false, //录音状态
    recordType: '',
    checkboxList: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // if (options.checkboxList) {
    //     this.setData({
    //         checkboxList: JSON.parse(options.checkboxList)
    //     })
    // }
    this.setData({
      rolename: app.globalData.rolename
    })
    this.initRecord();
  },
  onShow() {
    if (wx.getStorageSync('checkboxList')) {
      this.setData({
        checkboxList: wx.getStorageSync('checkboxList')
      })
    }
  },
  onUnload() {
    wx.removeStorageSync('checkboxList')
  },

  // 单位选择弹窗打开
  onUnitSelection() {
    this.setData({
      showUnitSelection: true
    })
  },

  confirmUnitSelection(e) {
    const {
      showUnitSelection,
      orgInfo
    } = e.detail
    this.setData({
      showUnitSelection,
    })
    if (orgInfo && orgInfo.id) {
      if (orgInfo.id === this.data.orgId) return
      this.setData({
        orgId: orgInfo.id,
        orgName: orgInfo.orgName,
        checkboxList: []
      })

    }
  },
  bindinput1(e) {
    let handleWayValue = validateEmoji(e.detail.value.replace(/\s+/g, ''))
    if (handleWayValue.length > 100) {
      this.setData({
        handleWayValue: handleWayValue.substring(0, 100), //截取前200位
      })
      return;
    }
    this.setData({
      handleWayValue
    })
  },
  bindinput2(e) {
    let handleOptionValue = validateEmoji(e.detail.value.replace(/\s+/g, ''))
    if (handleOptionValue.length > 50) {
      this.setData({
        handleOptionValue: handleOptionValue.substring(0, 50), //截取前200位
      })
      return;
    }
    this.setData({
      handleOptionValue
    })
  },
  // 选择设备
  onChoseDevices() {
    if (!this.data.orgId && !app.globalData.isProprietor) return showMsg("请先选择单位")
    wx.navigateTo({
      url: `/pages/index-inside-page/choseDevice/choseDevice?orgId=${this.data.orgId}`,
    })
  },
  onDropChange(e) {
    this.setData({
      handleWay: e.detail
    })
  },
  beforeRead(event) {
    console.log(event, "event");
    const {
      file,
      callback
    } = event.detail;
    callback(file.type === 'image' || file.type === 'video');
  },
  // 删除照片
  deletedFile(e) {
    let type = e.currentTarget.dataset.type
    if (type == 'image') {
      this.data.fileImageList.splice(e.detail.index, 1)
      this.setData({
        fileImageList: this.data.fileImageList
      })
    } else if (type == 'video') {
      this.data.fileVideoList.splice(e.detail.index, 1)
      this.setData({
        fileVideoList: this.data.fileVideoList
      })
    }
  },
  // 上传照片
  async afterRead(e) {
    console.log(e, 'e');
    let _this = this;
    let file = e.detail.file.url
    let type = e.currentTarget.dataset.type
    wx.uploadFile({
      url: app.globalData.reqUrl + 'file/upload',
      filePath: file,
      name: 'file',
      header: {
        "Content-Type": "multipart/form-data"
      },
      formData: {
        "token": app.globalData.token
      },
      success: function (res) {
        var res = JSON.parse(res.data)
        console.log(res);
        if (res.code == 20000) {
          if (type == 'image') {
            _this.data.fileImageList.push({
              url: res.data.url,
            })
            _this.setData({
              fileImageList: _this.data.fileImageList
            })
          } else if (type == 'video') {
            _this.data.fileVideoList.push({
              url: res.data.url,
            })
            _this.setData({
              fileVideoList: _this.data.fileVideoList
            })
          }
        } else if (res.statusCode != 20000) {
          wx.showModal({
            title: '提示',
            content: '上传失败',
            showCancel: false
          })
          return;
        }
      },
      fail: function (e) {
        wx.showModal({
          title: '提示',
          content: '上传失败',
          showCancel: false
        })
      }
    })
  },

  //识别语音 -- 初始化
  initRecord() {
    const _this = this;
    // 有新的识别内容返回，则会调用此事件
    manager.onRecognize = function (res) {
      console.log(res)
    }
    // 正常开始录音识别时会调用此事件
    manager.onStart = (res) => {
      console.log("成功开始录音识别", res)
    }
    // 识别错误事件
    manager.onError = (res) => {
      console.error("error msg", res)
    }
    //识别结束事件
    manager.onStop = (res) => {
      console.log(res, "res");
      console.log('..............结束录音')
      console.log('录音临时文件地址 -->' + res.tempFilePath);
      console.log('录音总时长 -->' + res.duration + 'ms');
      console.log('文件大小 --> ' + res.fileSize + 'B');
      console.log('语音内容 --> ' + res.result);
      if (res.result == '') {
        wx.showModal({
          title: '提示',
          content: '听不清楚，请重新说一遍！',
          showCancel: false,
          success: (res) => {}
        })
        return;
      }
      if (_this.data.recordType == 'handleWay') {
        var text = _this.data.handleWayValue + res.result;
        _this.setData({
          handleWayValue: text
        })
      } else {
        var text = _this.data.handleOptionValue + res.result;
        _this.setData({
          handleOptionValue: text
        })
      }
    }
  },
  //语音  --按住说话
  touchStart(e) {
    this.impower()
    this.setData({
      recordState: true, //录音状态
      recordType: e.currentTarget.dataset.type
    })
    // 语音开始识别
    manager.start({
      lang: 'zh_CN', // 识别的语言，目前支持zh_CN en_US zh_HK sichuanhua
    })
  },
  //录音授权
  impower() {
    var t = this;
    wx.authorize({
      scope: 'scope.record',
      success(res) {
        console.log("录音授权成功", res);
        //app.globalData.audioplay = true
        // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
        // wx.startRecord();
        t.recorderManager = wx.getRecorderManager();
        t.innerAudioContext = wx.createInnerAudioContext();

        // 为了防止苹果手机静音无法播放
        wx.setInnerAudioOption({
          obeyMuteSwitch: false
        })

        t.innerAudioContext.autoplay = true;

        console.log("wx.getRecorderManager()", wx.getRecorderManager())
        t.recorderManager.onStop(function (res) {
          console.log('recorder stop' + JSON.stringify(res));
          t.voicePath = res.tempFilePath;
        });
      },
      fail() {
        console.log("第一次录音授权失败");
        wx.showModal({
          title: '提示',
          content: '您未授权录音，功能将无法使用',
          showCancel: true,
          confirmText: "授权",
          confirmColor: "#AF1F25",
          success(res) {
            if (res.confirm) {
              //确认则打开设置页面（自动切到设置页）
              wx.openSetting({
                success: (res) => {
                  console.log(res.authSetting);
                  if (!res.authSetting['scope.record']) {
                    //未设置录音授权
                    console.log("未设置录音授权");
                    wx.showModal({
                      title: '提示',
                      content: '您未授权录音，功能将无法使用', // 可以自己编辑
                      showCancel: false,
                      success: function (res) {
                        console.log("不知道打印的啥？")
                      },
                    })
                  } else {
                    //第二次才成功授权
                    console.log("设置录音授权成功");
                    //app.globalData.audioplay = true;
                    t.recorderManager = wx.getRecorderManager();
                    t.innerAudioContext = wx.createInnerAudioContext();

                    // 为了防止苹果手机静音无法播放
                    wx.setInnerAudioOption({
                      obeyMuteSwitch: false
                    })

                    t.innerAudioContext.autoplay = true;

                    console.log("wx.getRecorderManager()", wx.getRecorderManager())
                    t.recorderManager.onStop(function (res) {
                      console.log('recorder stop' + JSON.stringify(res));
                      t.voicePath = res.tempFilePath;
                    });
                  }
                },
                fail: function () {
                  console.log("授权设置录音失败");
                }
              })
            } else if (res.cancel) {
              console.log("cancel");
            }
          },
          fail() {
            console.log("openfail");
          }
        })
      }
    })
  },
  //语音  --松开结束
  touchEnd(e) {
    this.setData({
      recordState: false
    })
    // 语音结束识别
    manager.stop();
  },

  onDel(e) {
    console.log(e, "e");
    // let imei = e.currentTarget.dataset.imei
    let index = e.currentTarget.dataset.index
    this.data.checkboxList.splice(index, 1)
    this.setData({
      checkboxList: this.data.checkboxList
    })
  },
  async onSave() {
    if (!this.data.checkboxList.length) return showMsg('请添加设备')
    if (this.data.handleWayValue == '') return showMsg('隐患描述不能为空')
    let picList = []
    if (this.data.fileImageList.length) {
      this.data.fileImageList.forEach(item => {
        picList.push(item.url)
      })
    }
    let videoFile = ''
    if (this.data.fileVideoList.length) {
      this.data.fileVideoList.forEach(item => {
        videoFile = item.url
      })
    }
    let res = await reqhiddenDangerAdd({
      imeiList: this.data.checkboxList,
      userId: app.globalData.userId,
      type: this.data.handleWay,
      content: this.data.handleWayValue,
      picList: picList,
      videoFile: videoFile,
      // handleResult: this.data.handleWay == 0 ? this.data.handleOptionValue : '',
    })
    if (res.code !== 20000) return showMsg(res.message)
    showMsg("上报成功", "success")
    setTimeout(() => {
      wx.navigateBack({
        delta: 1,
      })
    }, 1000)
    // wx.switchTab({
    //     url: '/pages/index/index',
    // })
  },
})